package com.wcity.manage.web.community;

import com.alibaba.fastjson.JSON;
import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.enums.SaveImageType;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.vo.community.activity.ActivityVo;
import com.wcity.manage.common.vo.community.partybuilding.PartyBuildingVo;
import com.wcity.manage.common.vo.community.permit.ConsultationVo;
import com.wcity.manage.common.vo.community.permit.PermitVo;
import com.wcity.manage.common.vo.community.survey.SurveyVo;
import com.wcity.manage.common.vo.community.volunteer.VolunteerVo;
import com.wcity.manage.common.vo.community.workguide.WorkGuideVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.Register;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.image.ImageUrl;
import com.wcity.manage.dao.model.community.survey.Survey;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.community.image.ImageService;
import com.wcity.manage.service.community.survey.SurveyService;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 社区概况
 * Created by hgg on 2016/12/15.
 */
@Controller
public class SurveyAct {

    private final static Logger log = LoggerFactory.getLogger( SurveyAct.class );

    @Autowired
    private SurveyService surveyService;

    @Autowired
    private BlockService blockService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private RegisterService registerService;

    /**
     * 社区概况列表
     * @param request
     * @return
     */
    @RequestMapping(value = "survey_list")
    public String surveyList( HttpServletRequest request,PageModel model,HttpServletResponse response ){

        try {

            //【1】获取参数
            Map<String,Object> requestMap = RequestUtil.getGetData(request);

            //【2】查询数据
            requestMap.put( "start",(model.getPageNum()-1)*model.getNumPerPage() );
            requestMap.put( "end",model.getNumPerPage() );
            requestMap.put( "parentId",0 );

            //【3】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }
            requestMap.put( "userId",user.getId() );
            List<SurveyVo> surveys = surveyService.surveys( requestMap );

            //【4】查询总数量
            Integer totalSurvey = surveyService.surveyTotal( requestMap );
            model.setTotal( totalSurvey );

            request.setAttribute( "surveys",surveys );
            request.setAttribute( "pageModel",model );
            request.setAttribute( "blockName",requestMap.get( "blockName" ) );
        }catch ( Exception e ){
            log.error( "查询社区概况列表异常:" + e.getMessage() );
        }
        return "community/survey-list";
    }

    /**
     * 执行删除社区概况
     * @param request
     */
    @RequestMapping(value = "delete_community_survey")
    @ResponseBody
    public void deleteSurvey( HttpServletRequest request,HttpServletResponse response ){

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String,Object> requestMap = RequestUtil.getGetData(request);
            if( requestMap.get( "id" ) == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", "" ) );
                return ;
            }

            //【2】执行删除
            Integer deleteNum = surveyService.deleteSurvey( requestMap );
            if( deleteNum == 0 ){
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        }catch ( Exception e ){
            log.error( "删除社区概况异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "", "", "", "" ) );
    }

    /**
     * 新增社区概况
     * @param survey
     * @param response
     */
    @RequestMapping(value = "add_community_survey")
    @ResponseBody
    public void addSurvey( Survey survey,HttpServletResponse response,HttpServletRequest request ){

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            String blockId = request.getParameter("blockId");
            String imageUrl = request.getParameter( "imageUrl" );
            //【1】校验参数
            if( StringUtils.isBlank( survey.getCommunityContent() ) || StringUtils.isBlank( blockId ) ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return ;
            }
            //【2】获取用户
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return ;
            }

            //【3】执行保存社区概况
            String[] blockIds = blockId.split( "," );
            survey.setUserId( user.getId() );
            surveyService.saveAddSurvey( survey,blockIds,imageUrl );

        }catch ( Exception e ){
            log.error( "保存社区概况异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "survey_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到编辑社区概况页面
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_survey")
    public String surveyDetail( HttpServletRequest request,HttpServletResponse response ){

        try {

            //【1】校验参数
            Map<String,Object> requestMap = RequestUtil.getGetData(request);
            if( requestMap.get( "id" ) == null ){
                return null;
            }
            //【2】获取用户
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询社区概况数据
            requestMap.put( "userId",user.getId() );
            requestMap.put( "parentId",0 );
            Survey survey = surveyService.surveyDetail( requestMap );
            request.setAttribute( "survey",survey );
            if( survey == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", "" ) );
                return null;
            }

            //【4】查询用户管理的未选择的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            String blocks = surveyService.blockIds( queryMap );
            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryNotBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blockNots",queryNotBlocks );

            //【5】查询用户管理的已选择的小区列表
            queryMap.put( "id",survey.getParentId() );
            blocks = surveyService.blockIds( queryMap );
            queryMap.put( "id",null );
            queryMap.put( "notContain",null );
            queryMap.put( "contain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

            //【6】查询封面
            Map<String,Object> queryImageMap = new HashedMap();
            queryImageMap.put( "referId",requestMap.get( "id" ) );
            queryImageMap.put( "saveType", SaveImageType.COMMUNITY_SURVEY );
            List<ImageUrl> imageUrls = imageService.images( queryImageMap );
            if( CollectionUtils.isNotEmpty( imageUrls ) ){
                request.setAttribute( "image",imageUrls.get(0) );
            }

        }catch ( Exception e ){
            log.error( "查询社区概况失败: " + e.getMessage() );
            RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", "" ) );
        }

        return "community/survey-edit";
    }

    /**
     * 更新社区概况
     * @param survey
     * @param response
     */
    @RequestMapping(value = "save_edit_community_survey")
    @ResponseBody
    public void updateSurvey( Survey survey,HttpServletResponse response,HttpServletRequest request ){

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            String blockId = request.getParameter("blockId");
            String imageUrl = request.getParameter( "imageUrl" );
            //【1】校验参数
            if( StringUtils.isBlank( survey.getCommunityContent() ) || StringUtils.isBlank( imageUrl )
                    || survey.getId() == null || survey.getId() == 0 || StringUtils.isBlank( blockId ) ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return ;
            }
            //【2】获取用户
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return ;
            }

            //【3】执行更新社区概况
            survey.setUserId( user.getId() );
            String[] blockIds = blockId.split( "," );
            Integer saveNum = surveyService.saveEditSurvey( survey,blockIds,imageUrl );
            if( saveNum == 0 ){
                throw new RuntimeException( "更新社区概况失败" );
            }

        }catch ( Exception e ){
            log.error( "更新社区概况异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "survey_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到添加概况的页面
     * @return
     */
    @RequestMapping(value = "to_add_survey")
    public String toAddSurvey( HttpServletRequest request,HttpServletResponse response ){

        try {

            //【1】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }
            //【2】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            String blockStr = surveyService.blockIds( queryMap );
            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blockStr );
            List<Block> blocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",blocks );
        }catch ( Exception e ){
            log.error( "获取小区列表异常：" + e.getMessage() );
        }
        return "community/survey-add";
    }

    /**
     * 跳转到概况详情的页面
     * @return
     */
    @RequestMapping(value = "to_detail_survey")
    public String toDetailSurvey( HttpServletRequest request,HttpServletResponse response ){

        try {

            //【1】校验参数
            Map<String,Object> requestMap = RequestUtil.getGetData(request);
            if( requestMap.get( "id" ) == null ){
                return null;
            }

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }
            //【3】查询社区概况数据
            requestMap.put( "userId",user.getId() );
            requestMap.put( "parentId",0 );
            Survey survey = surveyService.surveyDetail( requestMap );
            request.setAttribute( "survey",survey );
            if( survey == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", "" ) );
                return null;
            }

            //【4】查询当前社区概况包含的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "id",survey.getParentId() );
            String blocks = surveyService.blockIds( queryMap );
            queryMap.put( "id",null );
            queryMap.put( "notContain",null );
            queryMap.put( "contain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

            //【5】查询社区概况封面
            requestMap.clear();
            requestMap.put( "referId",survey.getId() );
            requestMap.put( "saveType",SaveImageType.COMMUNITY_SURVEY  );
            List<ImageUrl> imageUrls = imageService.images( requestMap );
            request.setAttribute( "imageUrls",imageUrls );

        }catch ( Exception e ){
            log.error( "获取社区概况详情异常：" + e.getMessage() );
        }
        return "community/survey-detail";
    }

/****************************************H5端请求处理****************************************************************/
    /**
     * 社区概况详情（H5）端
     * @return
     */
    @RequestMapping(value = "detail_survey_h5")
    @ResponseBody
    public Object detailSurvey( HttpServletRequest request,HttpServletResponse response ){

        //【1】校验参数
        Map<String,Object> requestMap = new HashedMap();
        String surveyId = request.getParameter( "surveyId" );
        if( StringUtils.isBlank( surveyId ) ){
            throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
        }

        //【2】获取当前用户信息
//        Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
//        if( userMap == null || userMap.get( "blockId" ) == null ){
//            throw new CustomException( "用户信息不存在", Code.ERROR );
//        }
        Block block = blockService.getBlockById( Integer.parseInt( surveyId ) );
        if( block == null ){
            throw new CustomException( "小区不存在", Code.ERROR );
        }
        //【3】查询社区概况数据
        requestMap.put( "userId",block.getUserId() );
        requestMap.put( "parentId",0 );
        requestMap.put( "communityId",block.getId() );
        Survey survey = surveyService.surveyDetail( requestMap );
        if( survey == null ){
            throw new CustomException( "社区概况不存在", Code.ERROR );
        }

        Map<String,Object> map = JSONUtil.getSuccessJson();
        map.put( "survey-content",survey.getCommunityContent() );

        //【4】查询社区封面
        requestMap.clear();
        requestMap.put( "referId",survey.getId() );
        requestMap.put( "saveType",SaveImageType.COMMUNITY_SURVEY );
        List<ImageUrl> imageUrls = imageService.images( requestMap );
        map.put( "imageUrls",imageUrls );
        return map;
    }
}
